package com.emisky.pictures.common;

import java.net.URL;
import java.util.Collection;
import java.util.UUID;

import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;

import com.emisky.pictures.common.exception.PictureException;

public class CommonUtils {
	/**
	 * 根据标示获取截图位置（顺时针0-8）
	 * @param flag
	 * @return 默认返回center
	 */
	public static Position getPosition(int flag,Position defaultPos){
		switch (flag) {
		case 0:
			return Positions.TOP_LEFT;
		case 1:
			return Positions.TOP_CENTER;
		case 2:
			return Positions.TOP_RIGHT;
		case 3:
			return Positions.CENTER_RIGHT;
		case 4:
			return Positions.BOTTOM_RIGHT;
		case 5:
			return Positions.BOTTOM_CENTER;
		case 6:
			return Positions.BOTTOM_LEFT;
		case 7:
			return Positions.CENTER_LEFT;
		case 8:
			return Positions.CENTER;
		default:
			
			break;
		}
		return defaultPos;
	}
	/**
	 * 创建PictureHelper
	 * @return
	 */
	public static PictureHelper buildPictureHelper(){
		return new PictureHelper();
	}
	/**
	 * 判断字符串是否为空
	 * @param value
	 * @return
	 */
	public static boolean isNullOrEmpty(String value){
		if(value==null || value==""){
			return true;
		}
		return false;
	}
	/**
	 * 判断集合是否为空
	 * @param value
	 * @return
	 */
	public  static <T> boolean isNullOrEmpty(Collection<T> value){
		if(value==null || value.size()==0){
			return true;
		}
		return false;
	}
	/**
	 * 获取文件后缀名 如果没有后缀则返回jpg
	 * @param fileName
	 * @return
	 */
	public static String getSuffix(String fileName){
		if(CommonUtils.isNullOrEmpty(fileName)){
			throw new PictureException("fileName 文件名为空");
		}
		String[] fileParts= fileName.split("\\.");
		if(fileParts.length<2){
			throw new PictureException("不正确的文件名");
		}
		String suffix=fileParts[fileParts.length-1];
		return isNullOrEmpty(suffix)?"jpg":suffix;
	}
	/**
	 * 生成唯一guid
	 * @return
	 */
	public static String buildGuid(){
		UUID uuid=UUID.randomUUID();
		return uuid.toString().replaceAll("-", "").toLowerCase();
	}
	
	/**
	 * 获取当前根路径 ，
	 * web项目返回WEB-INF上目录
	 * 如果不包含/WEB-INF/的返回结尾去掉‘/’的路径
	 * @return 
	 */
	public static String getRootPath(){
		URL classUrl= Thread.currentThread().getContextClassLoader().getResource("");
		String classAbsPath=classUrl.getPath();
		int indexFlag=classAbsPath.indexOf("/WEB-INF/");
		if(indexFlag!=-1){
			classAbsPath= classAbsPath.substring(0,indexFlag);
		}
		if(classAbsPath.endsWith("/")){
			classAbsPath=classAbsPath.substring(0,classAbsPath.lastIndexOf("/"));
		}
		return classAbsPath;
	}
	/**
	 * 解析路径，替换动态路径
	 * @param path
	 * @return
	 */
	public static String parsePath(String path){
		if(isNullOrEmpty(path)){
			return path;
		}
		path=path.replaceAll("\\$\\{root\\}", getRootPath());
		return path;
	}
}
